use web_sys::{Window, Document, Element, HtmlInputElement, HtmlCollection};
use wasm_bindgen::JsCast;
use super::Console;

pub struct Query;

impl Query {

    pub fn find_by_id(field: &'static str) -> Option<HtmlInputElement> {
        let window: Window = if let Some(v) = web_sys::window() { v } else {
            Console::error("无法获取 windows 对象");
            return None;
        };
        let document: Document = if let Some(v) = window.document() { v } else {
            Console::error("无法获取 Document 对象");
            return None;
        };
        let e: Element = if let Some(v) = document.get_element_by_id(field) { v } else {
            let message = &format!("无法获取 id 为 {} 的元素", field);
            Console::error(message);
            return None;
        };
        let input: HtmlInputElement = if let Ok(v) = e.dyn_into::<HtmlInputElement>() { v } else {
            let message = &format!("转换元素 {} 为 HtmlInputElement 失败", field);
            Console::error(message);
            return None;
        };
        Some(input)
    }

    pub fn value_by_id(field: &'static str) -> String {
        if let Some(v) = Self::find_by_id(field) { v.value() } else {
            "".to_owned()
        }
    }

    pub fn bind<T: Fn(&Element)>(callback: T) {
        let window: Window = if let Some(v) = web_sys::window() { v } else {
            Console::error("无法获取 windows 对象");
            return;
        };
        let document: Document = if let Some(v) = window.document() { v } else {
            Console::error("无法获取 Document 对象");
            return;
        };

        let elements: HtmlCollection = document.get_elements_by_tag_name("tbody");
        if elements.length() == 0 {
            return;
        }
        let item = elements.item(0).unwrap();
        callback(&item);
    }
}
